package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/liangchao/blogo/src/admin/forms"
	"github.com/liangchao/blogo/src/common/Response"
	"github.com/liangchao/blogo/src/common/dao"
	"github.com/liangchao/blogo/src/common/models"
	"github.com/liangchao/blogo/src/common/utils"
	"net/http"
)

func GetLoginPage(c *gin.Context) {
	c.HTML(http.StatusOK, "template/login.html", gin.H{
		"title": "blogo：login page",
	})
}

// 登录逻辑
func DoLogin(c *gin.Context) {
	// 解析字段
	PasswordLoginForm := forms.PasswordLoginForm{}

	//if err := c.ShouldBind(&PasswordLoginForm); err!=nil {
	//utils.HandleValidatorError(c, err)
	//return
	//}
	PasswordLoginForm.Username = c.Query("username")
	PasswordLoginForm.Password = c.Query("password")
	PasswordLoginForm.Captcha = c.Query("captcha")
	PasswordLoginForm.CaptchaId = c.Query("captchaId")

	fmt.Println("form: ", PasswordLoginForm)

	if !store.Verify(PasswordLoginForm.CaptchaId, PasswordLoginForm.Captcha, true) {
		Response.Err(c, 200, 400, "验证码错误", "")
		return
	}

	user, ok := new(dao.UserDao).FindUserInfo(PasswordLoginForm.Username, PasswordLoginForm.Password)
	if !ok {
		Response.Err(c, 200, 401, "用户未注册或密码错误", "")
		return
	}

	token := utils.CreateToken(c, user.AdminUserId, user.NickName, user.Locked)
	userinfoMap := HandleUserModelTopMap(user)
	userinfoMap["token"] = token

	Response.Success(c, http.StatusOK, "success", userinfoMap)
	//c.Header("x-token", token)
	//c.Redirect(http.StatusMovedPermanently, "/blogo/dashboard/page")

}

func HandleUserModelTopMap(user *models.User) map[string]interface{} {
	userItemMap := map[string]interface{}{
		"id":        user.AdminUserId,
		"username":  user.LoginUserName,
		"nick_name": user.NickName,
	}
	return userItemMap
}
